//
//  WBMainViewController.swift
//  Weibo-Swift
//
//  Created by law on 2018/6/1.
//  Copyright © 2018年 JKing. All rights reserved.
//

import UIKit

class WBMainViewController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.random()
        
        setupChildControllers()
        setupComposeButton()
        
    }
    
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return .portrait
    }
    
    // MARK: - 监听方法
    // 撰写微博
    // @objc 允许这个函数在【运行时】通过OC的消息机制被调用
    @objc private func composeStatus() {
        print("------")
        
        let vc = UIViewController()
        vc.view.backgroundColor = UIColor.random()
        
        let nav = UINavigationController(rootViewController: vc)
        present(nav, animated: true, completion: nil)
        
    }
    
    // MARK: - 私有控件
    private lazy var composeButton: UIButton = UIButton.init(imageName: "tabbar_compose_icon_add", backImageName: "tabbar_compose_button")
    
}

extension WBMainViewController {
    
    private func setupComposeButton() {
        
        tabBar.addSubview(composeButton)
        
        let count = CGFloat((viewControllers?.count)!)
        let w = view.bounds.size.width / count - 1
        
        composeButton.frame = tabBar.bounds.insetBy(dx: w*2, dy: 0)
        composeButton.addTarget(self, action: #selector(composeStatus), for: .touchUpInside)
        print("按钮宽度\(composeButton.frame.width)")
    }
    
    private func setupChildControllers() {
        
        // 先从沙盒读取数据
        let docDir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        let jsonPath = (docDir as NSString).appendingPathComponent("main_tabbar.json")
        var data = NSData(contentsOfFile: jsonPath)
        
        // 沙盒未读取到 从bundle加载
        if data == nil {
            
            let path = Bundle.main.path(forResource: "main_tabbar.json", ofType: nil)
            data = NSData(contentsOfFile: path!)
        }
        
        // 加载json数据
        guard let array = try? JSONSerialization.jsonObject(with: data! as Data, options: []) as? [[String: Any]] else {
            return
        }
        
        // 遍历数组创建控制器
        var arrayM = [UIViewController]()
        for dict in array! {
            arrayM.append(controller(dict: dict))
        }
        viewControllers = arrayM
    
    }
    
    private func controller(dict: [String: Any]) -> UIViewController {
        
        guard let clsName = dict["clsName"] as? String,
            let title = dict["title"] as? String,
            let imageName = dict["imageName"] as? String,
            let cls = NSClassFromString(Bundle.main.namespace + "." + clsName) as? WBBaseViewController.Type,
            let visitorInfo = dict["visitorInfo"] as? [String : String]
            
            else {
                return UIViewController()
        }
        
        let vc = cls.init()
        vc.title = title
        vc.tabBarItem.image = UIImage(named: "tabbar_" + imageName)
        vc.tabBarItem.selectedImage = UIImage(named: "tabbar_" + imageName + "_highlighted")?.withRenderingMode(.alwaysOriginal)
        
        vc.tabBarItem.setTitleTextAttributes([.foregroundColor: UIColor.orange], for: UIControlState.highlighted)
        
        vc.visitorInfo = visitorInfo
        
        let nav = WBNavigationController.init(rootViewController: vc)
        
        return nav
    }
    
}
